require 'uri'

class Core < ActiveRecord::Base
  belongs_to :resource, :polymorphic => true
  validates_less_reverse_captcha
  before_validation_on_create :generate_alias
  
  acts_as_taggable

  belongs_to :forum_topic
  belongs_to :user
  
  has_many :histories  
  has_many :reviews
  has_many :votes, :dependent => :destroy  
  has_many :bugs, :dependent => :destroy
  
  belongs_to :image, :class_name => 'Multimedia', :foreign_key => 'image_id'
  
  #has_many :multimedias, :class_name => 'Multimedia'
  
  has_and_belongs_to_many :multimedias, :foreign_key => 'core_id', :association_foreign_key => 'multimedia_id'
  
  has_and_belongs_to_many :kinds, :foreign_key => 'core_id', :association_foreign_key => 'kind_id'
  
  has_and_belongs_to_many :albums, :foreign_key => 'core_id', :association_foreign_key => 'album_id'  
  
  has_and_belongs_to_many :bookmarks, :class_name => "User", 
      :foreign_key => 'core_id', :association_foreign_key => 'user_id'
  
  validates_presence_of :name
  
  validates_uniqueness_of   :alias,    :if => Proc.new { |user| !user.name.blank? }
  
  validates_format_of :email, :with => Authentication.email_regex, :if => Proc.new { |core| !core.email.blank? }
  #validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  
 
  default_value_for :is_blocked, false
  default_value_for :readings, 0
  default_value_for :is_backup, false
  default_value_for :vote, 0

  validate :must_have_kinds


  
    
  before_update :backup

  def set_image multimedia
     if multimedia.photo_file_name
        self.image_id = multimedia.id        
        self.save
     end
  end
  
  def photos_attributes=(attributes)    
    photo = TempPhoto.new(attributes)    
    if photo.data_file_name || !attributes[:data_url].blank?            
      photo.user = self.user
     self.multimedias << photo      
     self.image = self.multimedias.last 
    end
  end
  
  def site=(site)
    l = []
    site.each do |i| 
      if i.strip != "" 
        if(!(i.strip =~ URI::regexp).nil?)
          l << i.strip         
        elsif !(("http://" + i.strip =~ URI::regexp).nil?)
          l << "http://" + i.strip
        end        
      end      
    end  
    self.sites = l.join(" , ") 
  end
  
  def backup
    
  end
  
  def kindsids
    kind_ids.join(',') + ","
  end
  
  def kindsids=(kindsids)
    kindsids = kindsids[0, kindsids.length - 1] unless (kindsids.blank?)
    self.kind_ids = kindsids.split(',')
  end
  
  def generate_alias    
     a = self.name.blank? ? "noname" : self.name.gsub('è','e').gsub('à','a').gsub('ò','o').gsub('ì','i').gsub('ù','u').gsub(/[^a-zA-Z0-9_ -]/, '').gsub(' ','-').downcase     
    if(not Core.find(:first, :conditions => ["alias = ?", a]) and 
      ((!self.alias.blank? and self.new_record?) || !self.new_record?))
      self.alias = a
    else
      self.alias = Time.now.utc.to_i.to_s + "-" + a
    end        
  end

  def get_avatar style
     if self.image
       self.image.data.url(style) 
     else "0" + self.class.to_s + ".gif"
     end
  end 
  
  def is_rewritable user
    true
  end
  
  private
  
  def must_have_kinds
      errors.add_to_base(I18n.t "core.a_kind_at_least") if self.kinds.size == 0
      errors.add_to_base(I18n.t "core.three_kinds_max") if self.kinds.size > 3
  end

  
end
